package com.animallife.android.service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.animallife.android.util.Config;
import com.animallife.android.util.HttpConnector;
import com.animallife.android.util.JSONParser;

/**
 * DataUpdateService - manages connection to server, retrieves data from it,
 * parses the response and updates database with new values in background
 * thread.
 */
public class UpdateService extends IntentService {

	private static final String TAG = UpdateService.class.getSimpleName();

	public static final String EXTRA_STATUS_RECEIVER = "extra_receiver";
	public static final String EXTRA_REQUEST_CODE = "request_code";
	public static final String ERROR_MESSAGE = "err_msg";
	public static final String RECORDS = "records";

	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_ERROR = 2;
	public static final int STATUS_FINISHED = 3;

	private JSONParser jsonParser;

	private int queryCode;

	private final HttpConnector connector;

	public UpdateService() {
		super(TAG);
		connector = HttpConnector.getInstance();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		// resolver = getBaseContext().getContentResolver();
		jsonParser = new JSONParser();
		// prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}

	/**
	 * This method manages sends request to a server, parses response from it
	 * and updates database with new values.
	 */
	@Override
	protected void onHandleIntent(final Intent intent) {

		final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		if (null != receiver)
			receiver.send(STATUS_RUNNING, null);

		queryCode = intent.getIntExtra(EXTRA_REQUEST_CODE, -1);
		final Bundle resultData = new Bundle();
		String url;
		String response = "";

		try {
			switch (queryCode) {

			case Config.IMAGE_FETCH:

				String username = intent.getStringExtra(Config.ANIMAL_NAME);
				url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + URLEncoder.encode(username) + "&imgsz=large&as_filetype=jpg";
				response = connector.sendGETRequest(url);
				resultData.putStringArray(Config.URLS_ARRAY, jsonParser.getImageUrlsArray(new JSONObject(response)));
				receiver.send(STATUS_FINISHED, resultData);
				break;

			default:
				break;
			}

		} catch (URISyntaxException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "Unable to connect server...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (ClientProtocolException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (IOException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			final Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		}
	}
}
